/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package grex.fitnessfunctions.ErrorFunctions;

import grex.GP;
import grex.IPredictiveModel;
import grex.Data.Prediction;
import grex.Data.PredictionContainer;
import grex.fitnessfunctions.FitnessFunction;
import grex.fitnessfunctions.IFitnessFunction;
import grex.Nodes.Node;
import grex.Nodes.GeneException;
import grex.Nodes.TargetPred;

/**
 *
 * @author RIK
 */
public class MeasureAvgProb extends FitnessFunction{

    public MeasureAvgProb() {
        super("AvgP");
    }
    
    @Override
    protected double calcPredictionError(Prediction prediction, double targetValue) {
        return 0;
    }
    
    @Override
    protected double calcFinalError(PredictionContainer pc){
        if(model!=null && model instanceof GP){
            return(getAvgProb(((GP)model).getHead()));            
        }
        return -1;
    }
    
    protected double getAvgProb(Node gene){
        double n = getNrOfLeaves(gene);
        double p = getTotalProb(gene);
        return p/n;
    }
     
    protected double getTotalProb(Node gene) {
        Node[] children = gene.getChildren();
        if (children == null) {
            return getProb(((TargetPred)gene).getProbs());
        } else {
            double left = getTotalProb(children[1]);
            double right = getTotalProb(children[2]);
            return left + right;
        }
    }
    
    protected double getNrOfLeaves(Node gene) {
        Node[] children = gene.getChildren();
        if (children == null) {
            return 1;
        } else {
            double left = getNrOfLeaves(children[1]);
            double right = getNrOfLeaves(children[2]);
            return left + right;
        }
    }
    
    protected double getProb(double[] probs){
        double max =0;
        for (int i = 0; i < probs.length; i++) {
            max = Math.max(max, probs[i]);            
        }
        return max;
    }   
    
    public String getName(){
        return "AvgP";
    }


    
}
